<template>
  <div class="function-editor">
    <!-- 头部控制区 -->
    <div class="editor-header">
      <h2>{{ componentName }} (v{{ currentVersion }})</h2>
      <div class="actions">
        <el-button type="primary" size="small" :icon="saveIcon" @click="saveDraft">保存草稿</el-button>
        <el-button type="primary" size="small" :icon="commitIcon" @click="submitVersion" :disabled="!isValid">提交版本</el-button>
      </div>
    </div>

    <!-- 页签导航 -->
    <el-tabs v-model="activeTab">
      <el-tab-pane label="基本信息" name="businessComponent">
        <BasicInfoEditor v-model="draft.businessComponent"/>
      </el-tab-pane>
      <el-tab-pane label="参数定义" name="businessComponeParametersVersion">
        <ParameterEditor v-model="draft.businessComponeParametersVersions"/>
      </el-tab-pane>
      <el-tab-pane label="流程图" name="businessComponentFlow">
        <FlowchartDesigner v-model="draft.businessComponent.designScript"/>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts" setup>
import {ref, computed, onMounted, watch, reactive} from 'vue'
import BasicInfoEditor from "./baseinfoeditor.vue"
import ParameterEditor from "../businesscomponeparametersversion/index.vue"
import FlowchartDesigner from "./buscomponentdesigner"
import {useRoute} from "vue-router";
import {getBusinessComponent,commitadd,commitupdate,draftadd,draftupdate} from "@/api/business/businesscomponent";
import {listTenantFunctionVersion} from "@/api/business/tenantfunctionversion";
import {listBusinessComponeParametersVersion} from "@/api/business/businesscomponeparametersversion";
import { useIcon } from "@/components/common/util";
import { ElMessage } from 'element-plus';
import {getStringLength} from "@/utils/ruoyi";

// 类型定义
interface BusinessComponent {
  id:null,
  enterpriseCode:null,
  componentCode:null,
  componentName:null,
  componentIconUrl:null,
  remark:null,
  status:null,
  sortNumber:null,
  createBy:null,
  createTime:null,
  updateBy:null,
  updateTime:null,
  commitMessage:null,
  groovySource:null,
  designScript:null,
  fullGroovySource:null,
  isReturnvalue:null,
  returnType:null,
  isCurrent:null,
  version:null,
}
// 参数定义
interface BusinessComponeParametersVersion {
  parameterId:string,
  enterpriseCode:string,
  className:string,
  functionCode:string,
  parameterCode:string,
  parameterName:string,
  parameterType:string,
  sortNumber:string,
}

interface BusinessComponentFlow {
  designScript: string,
  isReturnvalue:string,
  returnType:string,
  commitMessage:string
}

interface FunctionDraft {
  businessComponent: BusinessComponent
  businessComponeParametersVersions: BusinessComponeParametersVersion[]
  businessComponentFlow: BusinessComponentFlow
}

// 状态管理
const activeTab = ref<'businessComponent' | 'businessComponeParametersVersion' | 'businessComponentFlow'>('businessComponent')
const route = useRoute();
const bscomponentId = ref(route.params.bscomponentId);
const saveIcon = useIcon('ali_save');
const commitIcon = useIcon('ali_commit');
const draft = ref<FunctionDraft>({
  businessComponent: reactive({
    componentCode:'',
    componentName:'', remark:'',
    status:'', version:'', isReturnvalue:'',
    returnType:'', commitMessage:''}),
  businessComponeParametersVersions: [],
  businessComponentFlow: {designScript:"{}"}
})

// 计算属性
const isValid = computed(() => {
  return !!draft.value.businessComponent.componentName &&
      // draft.value.businessComponeParametersVersion.length > 0 &&
      getStringLength(draft.value.businessComponent.designScript) > 0
})

// 从路由或props获取的示例数据
const componentName = ref('未命名')
const currentVersion = ref('1.0')
draft.businessComponent
watch(() => draft.value.businessComponent.designScript, (newVal) => {
  console.log('designScript changed:', newVal)
}, { deep: true })
// 方法
const saveDraft = () => {
  draft.value.businessComponent.isReturnvalue = draft.value.businessComponent.isReturnvalue;
  draft.value.businessComponent.returnType = draft.value.businessComponent.returnType;
  draft.value.businessComponent.commitMessage = draft.value.businessComponent.commitMessage;
  if(!draft.value.businessComponent.id){
    draftadd(draft.value).then(response=>{
      if(response.code==200){
            bscomponentId.value = response.data;
            loadBusinessComponet();
            ElMessage.success("保存成功!");
          }else{
            ElMessage.error("保存失败!");
          }
    })
  }else{
    draftupdate(draft.value).then(response=>{
      if(response.code==200){
            ElMessage.success("保存成功!");
          }else{
            ElMessage.error("保存失败!");
          }
    })
  }
}

const submitVersion = () => {
  if (!isValid.value) return
  draft.value.businessComponent.isReturnvalue = draft.value.businessComponent.isReturnvalue;
  draft.value.businessComponent.returnType = draft.value.businessComponent.returnType;
  draft.value.businessComponent.commitMessage = draft.value.businessComponent.commitMessage;
  //设置提交状态
  draft.value.businessComponent.status = '01';
  if(!draft.value.businessComponent.bscomponentId){
    commitadd(draft.value).then(response=>{
      if(response.code==200){
            bscomponentId.value = response.data;
            loadBusinessComponet();
            ElMessage.success("提交成功");
          }else{
            ElMessage.error("提交失败!");
          }
        })
  }else{
    commitupdate(draft.value).then(response=>{
      if(response.code==200){
        loadBusinessComponet();
            ElMessage.success("提交成功");
          }else{
            ElMessage.error("提交失败!");
          }
        })
  }
}
const loadBusinessComponet = async () => {
  try {
    console.log('loadBusinessComponet')
    //查询函数基本信息
    if(bscomponentId.value>0){
    const response = await getBusinessComponent(bscomponentId.value);
    if(response.data) {
      const data = response.data;
      // draft.value.businessComponent = data;
      Object.assign(draft.value.businessComponent, data || {})
      console.log('draft.value.businessComponent:', JSON.stringify(draft.value.businessComponent))
      componentName.value = draft.value.businessComponent.componentName;
      currentVersion.value = draft.value.businessComponent.version;


      //查询当前版本函数参数
      const paramResponse = await listBusinessComponeParametersVersion({
        componentCode: data.componentCode,
        version: data.version
      });
      if (paramResponse.code == 200) {
        draft.value.businessComponeParametersVersions = paramResponse.rows;
        draft.value.businessComponent.isReturnvalue = draft.value.businessComponent.isReturnvalue;
        draft.value.businessComponent.returnType = draft.value.businessComponent.returnType;
        draft.value.businessComponent.commitMessage = draft.value.businessComponent.commitMessage;
      }
    }
    }

  } catch (e) {
    console.log('Failed to load loadBusinessComponet data:', e);
  }
}
// 组件挂载时获取数据
onMounted(() => {
  loadBusinessComponet();
})
watch(
    () => route.params.componentId,
    (newValue, oldValue) => {
      // 当路由参数发生变化时，更新组件数据
      console.log('参数发生变化，更新数据：', newValue, oldValue);
      if(typeof newValue !==  'undefined') {
        bscomponentId.value = newValue;
        loadBusinessComponet()
      }

    }

)
</script>

<style scoped>
.function-editor {
  /* 样式保持不变 */
}
</style>
